package com.guimin.site.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fasterxml.jackson.databind.util.BeanUtil;
import com.guimin.common.util.SnowflakeIdWorker;
import com.guimin.common.util.exception.BaseException;
import com.guimin.common.vo.R;
import com.guimin.fuwu.entity.GuiminService;
import com.guimin.fuwu.service.impl.GuiminServiceServiceImpl;
import com.guimin.fuwu.vo.serveListVo;
import com.guimin.site.entity.GuiminSite;
import com.guimin.site.dao.GuiminSiteDao;
import com.guimin.site.service.GuiminSiteService;
import com.guimin.site.vo.SiteServeVo;
import com.guimin.site.vo.SiteVo;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.PageRequest;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * (GuiminSite)表服务实现类
 *
 * @author makejava
 * @since 2021-11-17 10:11:31
 */
@Service
public class GuiminSiteServiceImpl extends ServiceImpl<GuiminSiteDao, GuiminSite> implements GuiminSiteService {

    @Resource
    private GuiminSiteDao guiminSiteDao;
    @Resource
    private GuiminServiceServiceImpl getBaseImg;

    /**
     * 雪花id生成器
     */
    private SnowflakeIdWorker snowflakeIdWorker = new SnowflakeIdWorker(0, 0);
    private static final long START_TIMESTAMP = 1625068800000L;
    /**
     * 生成订单id
     *
     * @return 订单id
     */
    public synchronized long nextId() {
        return snowflakeIdWorker.nextId(START_TIMESTAMP);
    }

    /**
     * 获取站点列表
     * @param id
     * @return
     */
    public List<GuiminSite> getSiteList(Long id) {
        try {
            if(id == null){
                throw new BaseException("id为空");
            }
            QueryWrapper<GuiminSite> wrapper = new QueryWrapper<>();
            wrapper.eq("user_id",id);
            List<GuiminSite> sites = guiminSiteDao.selectList(wrapper);
            if(sites.size() > 0){
                return sites;
            }else {
                return null;
            }
        }catch (Exception e){
            throw new BaseException("网络错误");
        }
    }

    /**
     * 添加站点管理
     * @param id
     * @param site
     * @return
     */
    public R<?> addSiteData(Long id, SiteVo site) {
        try {
            ArrayList<GuiminSite> arrayList = new ArrayList<>();

            QueryWrapper<GuiminSite> wrapper = new QueryWrapper<>();
            wrapper.eq("village_name",site.getVillageName());
            Integer integer = guiminSiteDao.selectCount(wrapper);

            if(integer != 0){
                return R.fail("该站点已存在");
            }

            GuiminSite gmSite = new GuiminSite();
            gmSite.setId(nextId());//id
            gmSite.setUserId(id);//用户id
            gmSite.setCreateDatetime(new Date());//创建时间
            gmSite.setVillageAddress(site.getVillageAddress());
            gmSite.setVillageAgent(site.getVillageAgent());
            gmSite.setVillageName(site.getVillageName());
            gmSite.setVillageProperty(site.getVillageProperty());
            gmSite.setArea(site.getArea());
            gmSite.setOnly("唯一");
            if(site.getRecycleLists().size() == 0){
                gmSite.setLajiState("禁用");
            }else {
                //遍历废旧回收服务
                for (SiteVo.recycleList recycleList : site.getRecycleLists()){

                    GuiminSite Site = new GuiminSite();

                    Site.setId(nextId());//id
                    Site.setUserId(id);//用户id
                    Site.setCreateDatetime(new Date());//创建时间
                    Site.setVillageAddress(site.getVillageAddress());
                    Site.setVillageAgent(site.getVillageAgent());
                    Site.setVillageName(site.getVillageName());
                    Site.setVillageProperty(site.getVillageProperty());
                    Site.setArea(site.getArea());
                    Site.setRecyclesPrice(recycleList.getPrice());//废旧回收价格
                    Site.setRecyclesTwoId(recycleList.getId());//废旧回收id
                    Site.setRecyclesOneName(recycleList.getName());//废旧回收一级名称
                    Site.setRecyclesTwoName(recycleList.getTwoName());//废旧回收二级名称
                    Site.setRecyclesUnit(recycleList.getUnit());//废旧回收单位

                    //添加列表
                    arrayList.add(Site);
                }
            }
            if(site.getServeLists().size() == 0){
                System.out.println("走空");
                gmSite.setCgState("禁用");
            }else {
               // System.out.println("走循环");
                //遍历常规服务
                for (SiteVo.serveList list : site.getServeLists()){

                    GuiminSite guiminSite = new GuiminSite();

                    guiminSite.setId(nextId());//id
                    guiminSite.setUserId(id);//用户id
                    guiminSite.setCreateDatetime(new Date());//创建时间
                    guiminSite.setServe(list.getName());//服务名称
                    guiminSite.setServeType(list.getServeType());//服务类型
                    guiminSite.setLoveSet(list.getLoveSet());//爱心设置
                    guiminSite.setLoveEnergy(list.getLoveEnergy());//爱心
                    guiminSite.setSitePrice(list.getPrice());//价格
                    guiminSite.setFreeDate(list.getFreeDate());//免费日
                    guiminSite.setImgPath(list.getNotBase64ImgPath());//图片路径
                    guiminSite.setArea(site.getArea());
                    guiminSite.setVillageAddress(site.getVillageAddress());
                    guiminSite.setVillageAgent(site.getVillageAgent());
                    guiminSite.setVillageName(site.getVillageName());
                    guiminSite.setVillageProperty(site.getVillageProperty());

                    //添加列表
                    arrayList.add(guiminSite);
                }
            }
            arrayList.add(gmSite);
            System.out.println("数组一共有\n"+arrayList);

            //批量录入
            boolean batch = super.saveBatch(arrayList);
            if(batch == true){
                return R.success("添加成功");
            }else {
                return R.fail("添加失败");
            }
        }catch (Exception e){
            e.getMessage();
            throw new BaseException("添加失败，网络错误");
        }
    }

    /**
     * 按id删除
     * @param id
     * @return
     */
    public R<?> deleteSiteDate(Long id) {
        try {
            if(id == null){
                throw new BaseException("id为空");
            }
            int insert = guiminSiteDao.deleteById(id);
            if(insert > 0){
                return R.success("删除成功");
            }else {
                return R.fail("删除失败");
            }
        }catch (Exception e){
            throw new BaseException("网络错误，删除失败");
        }
    }

    /**
     * 站点修改
     * @param id
     * @param site
     * @return
     */
    public R<?> reviseSite(Long id, GuiminSite site) {
        try {
            if(id == null){
                throw new BaseException("id为空");
            }
            if(site == null){
                throw new BaseException("请求参数为空");
            }
            site.setUpdateDatetime(new Date());
            QueryWrapper<GuiminSite> wrapper = new QueryWrapper<>();
            wrapper.eq("user_id",id);
            wrapper.eq("id",site.getId());
            GuiminSite guiminSite = new GuiminSite();
            guiminSite.setSitePrice(site.getSitePrice());
            int update = guiminSiteDao.update(guiminSite, wrapper);
            if(update > 0){
                return R.success("修改成功");
            }else {
                return  R.fail("修改失败");
            }

        }catch (Exception e){
            throw new BaseException("网络异常，修改失败");
        }
    }

    /**
     * 查询废旧回收服务
     * @param id
     * @param site
     * @return
     */
    public R<?> detailsSiteData(Long id, GuiminSite site) {
        try {
            QueryWrapper<GuiminSite> wrapper = new QueryWrapper<>();
            wrapper.eq("village_name",site.getVillageName());
            wrapper.eq("user_id",id);
            wrapper.isNotNull("recycles_two_name");
            List<GuiminSite> siteLaJi = guiminSiteDao.selectList(wrapper);
            if(siteLaJi.size() == 0){
                return R.fail("该站点暂无废旧回收服务");
            }else {
                return R.success("查询成功",siteLaJi);
            }
        }catch (Exception e){
            throw new BaseException("网络异常，查询失败");
        }
    }

    /**
     * 查询常规服务
     * @param id
     * @param site
     * @return
     */
    public R<?> ordinarySiteData(Long id, GuiminSite site) {
        try {
            QueryWrapper<GuiminSite> wrapper = new QueryWrapper<>();
            wrapper.eq("village_name",site.getVillageName());
            wrapper.eq("user_id",id);
            wrapper.isNotNull("serve");
            List<GuiminSite> siteLaJi = guiminSiteDao.selectList(wrapper);
            ArrayList<SiteServeVo> serveVos = new ArrayList<>();
            for (GuiminSite zhand : siteLaJi){
                SiteServeVo siteServeVo = new SiteServeVo();
                BeanUtils.copyProperties(zhand,siteServeVo);
                //base64转码
                String baseImg = getBaseImg.getBaseImg(zhand.getImgPath());
                siteServeVo.setImgPath(baseImg);//编码过
                serveVos.add(siteServeVo);
            }
            if(siteLaJi.size() == 0){
                return R.fail("该站点暂无常规服务");
            }else {
                return R.success("查询成功",serveVos);
            }
        }catch (Exception e){
            throw new BaseException("网络异常，查询失败");
        }
    }

    /**
     * 批量修改
     * @param sites
     * @return
     */
    public R<?> alterSiteList(List<GuiminSite> sites) {
        try {
            //按id批量修改
            boolean b = super.updateBatchById(sites);
            if(b == true){
                return R.success("编辑成功");
            }else {
                return R.fail("编辑失败");
            }
        }catch (Exception e){
            throw new BaseException("修改异常，请联系管理员");
        }
    }

    /**
     * 按名称删除站点
     * @param name
     * @return
     */
    public R<?> deleteSiteDateByName(String name) {
        try {
            if(name == null || name == ""){
                throw new BaseException("站点令牌为空");
            }
            QueryWrapper<GuiminSite> wrapper = new QueryWrapper<>();
            wrapper.eq("village_name",name);
            int insert = guiminSiteDao.delete(wrapper);
            if(insert > 0){
                return R.success("删除成功");
            }else {
                return R.fail("删除失败");
            }
        }catch (Exception e){
            throw new BaseException("网络错误，删除失败");
        }
    }

    /**
     * 添加站点常规服务
     * @param id
     * @param sitevo
     * @return
     */
    public R<?> addSiteOrdinaryServe(Long id, SiteVo sitevo) {
        try {

            ArrayList<GuiminSite> arrayList = new ArrayList<>();
            for (SiteVo.serveList site : sitevo.getServeLists()){
                QueryWrapper<GuiminSite> wrapper = new QueryWrapper<>();
                wrapper.eq("serve",site.getName());
                wrapper.eq("user_id",id);
                wrapper.eq("village_name",sitevo.getVillageName());
                Integer integer = guiminSiteDao.selectCount(wrapper);
                if(integer != 0){
                    return R.fail("服务"+"\""+site.getName()+"\""+"已存在，无需重复添加");
                }

                GuiminSite S1 = new GuiminSite();
                S1.setId(nextId());//id
                S1.setUserId(id);//用户id
                S1.setCreateDatetime(new Date());//创建时间
                S1.setServe(site.getName());//服务名称
                S1.setSitePrice(site.getPrice());//价格
                S1.setFreeDate(site.getFreeDate());//免费日
                S1.setImgPath(site.getNotBase64ImgPath());//图片路径

                S1.setArea(sitevo.getArea());
                S1.setVillageAddress(sitevo.getVillageAddress());
                S1.setVillageAgent(sitevo.getVillageAgent());
                S1.setVillageName(sitevo.getVillageName());
                S1.setVillageProperty(sitevo.getVillageProperty());

                arrayList.add(S1);
            }
            boolean batch = super.saveBatch(arrayList);
            if(batch == true){
                //修改常规服务状态
                QueryWrapper<GuiminSite> wrapper = new QueryWrapper<>();
                wrapper.eq("cg_state","禁用");
                wrapper.eq("village_name",sitevo.getVillageName());
                GuiminSite site = new GuiminSite();
                site.setCgState("开启");
                int update = guiminSiteDao.update(site, wrapper);
                if(update > 0){
                    return R.success("添加成功");
                }else {
                    System.out.println("修改服务状态失败");
                    return R.success("添加成功");
                }
            }else {
                return R.fail("添加失败");
            }
        }catch (Exception e){
            System.out.println( e.getMessage());
            System.out.println(e.toString());
           throw new BaseException("网络异常，请稍后重试");
        }
    }

    /**
     * 添加站点废旧回收服务
     * @param id
     * @param sitevo
     * @return
     */
    public R<?> addSiteLaJiServe(Long id, SiteVo sitevo) {
        try {
            ArrayList<GuiminSite> arrayList = new ArrayList<>();
            for (SiteVo.recycleList laji : sitevo.getRecycleLists()){
                QueryWrapper<GuiminSite> wrapper = new QueryWrapper<>();
                wrapper.eq("recycles_two_name",laji.getTwoName());
                wrapper.eq("user_id",id);
                wrapper.eq("village_name",sitevo.getVillageName());
                Integer integer = guiminSiteDao.selectCount(wrapper);
                if(integer != 0){
                    return R.fail("服务"+"\""+laji.getTwoName()+"\""+"已存在，无需重复添加");
                }

                GuiminSite S1 = new GuiminSite();
                S1.setId(nextId());//id
                S1.setUserId(id);//用户id
                S1.setCreateDatetime(new Date());//创建时间

                S1.setRecyclesPrice(laji.getPrice());//废旧回收价格
                S1.setRecyclesTwoId(laji.getId());//废旧回收id
                S1.setRecyclesOneName(laji.getName());//废旧回收一级名称
                S1.setRecyclesTwoName(laji.getTwoName());//废旧回收二级名称
                S1.setRecyclesUnit(laji.getUnit());//废旧回收单位

                S1.setArea(sitevo.getArea());
                S1.setVillageAddress(sitevo.getVillageAddress());
                S1.setVillageAgent(sitevo.getVillageAgent());
                S1.setVillageName(sitevo.getVillageName());
                S1.setVillageProperty(sitevo.getVillageProperty());

                arrayList.add(S1);
            }
            boolean batch = super.saveBatch(arrayList);
            if(batch == true){
                //修改常规服务状态
                QueryWrapper<GuiminSite> wrapper = new QueryWrapper<>();
                wrapper.eq("laji_state","禁用");
                wrapper.eq("village_name",sitevo.getVillageName());
                GuiminSite site = new GuiminSite();
                site.setLajiState("开启");
                int update = guiminSiteDao.update(site, wrapper);
                if(update > 0){
                    return R.success("添加成功");
                }else {
                    System.out.println("修改服务状态失败");
                    return R.success("添加成功");
                }
            }else {
                return R.fail("添加失败");
            }
        }catch (Exception e){
            throw new BaseException("网络异常，请稍后重试");
        }
    }
}
